package com.ayuan.blog.common;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;

import java.util.Date;

/**
 * Created by xiaozhu on 16/5/8.
 */
@Log4j2
public class WeChatUtil {
    static private String token = null;
    static private Date getTokenTime = null;
    static final private String APP_ID = "wxe2a6d867fc22c0f9";
    static final private String SECRET = "c15dbd7ef74780e85e66b428ab910a02";

    static final private String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    static final private String OAUTH2_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    static final private String USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";

    public static String getToken() {
        if (getTokenTime == null ||
                (new Date().getTime() - getTokenTime.getTime()) > 60 * 60 * 1000) {
            getTokenTime = new Date();
            token = getTokenFromWx();
        }
        return token;
    }

    private static String getTokenFromWx() {
        JSONObject jsonObject = HttpClientUtil.httpPost(String.format(GET_TOKEN_URL, APP_ID, SECRET), null, false);
        log.info("token response : " + jsonObject.toJSONString());
        return jsonObject.getString("access_token");
    }

    public static String getOpenIdByCode(String code) {
        JSONObject jsonObject = HttpClientUtil.httpPost(String.format(OAUTH2_ACCESS_TOKEN_URL, APP_ID, SECRET, code), null, false);
        return jsonObject.getString("openid");
    }

    public static JSONObject getUserInfoByOpenId(String openId) {
        return HttpClientUtil.httpPost(String.format(USER_INFO_URL, getToken(), openId), null, false);
    }
}
